package ttc.sftp.adapter;

import java.util.ArrayList;
import java.util.List;

import ttc.sftp.R;
import ttc.sftp.adapter.contextmenu.IconContextMenu;
import ttc.sftp.data.InstalledApp;
import ttc.sftp.data.SFile;
import ttc.sftp.data.VFile;
import ttc.sftp.search.LocalSearchDatabase;
import ttc.sftp.user.User;
import ttc.sftp.util.FileSupport;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;

public class MyPagerAdapter extends PagerAdapter {
	public enum PageType {
		sftp(0), local(1), favorit(2), search(3);
		private final int id;

		PageType(int id) {
			this.id = id;
		}

		public int getValue() {
			return id;
		}
	};

	private Boolean isSearch;
	private Cursor CursorSearch;
	public static int itemCurrentId = 0;
	private Resources res;
	private Activity mainActivity;
	public static IconContextMenu iconContextMenu;
	public ListView ltwLocal, ltwSftp;
	public LocalFileAdapter myListAdapter;
	public int nPage;
	public int pageCurrent;

	RemoteFileAdapter remoteFileAdapter;
	UserAdapter userAdapter;
	Context mContext;
	Boolean connect = false;

	public void setConnect(Boolean a) {
		this.connect = a;
	}

	public Boolean getConnect() {
		return this.connect;
	}

	public void SetContext(Context context) {
		mContext = context;
	}

	public int getCount() {
		return nPage;
	}

	public MyPagerAdapter(ChannelSftp channel1, Activity activity, Resources res) {
		isSearch = false;
		nPage = 3;
		channel = channel1;
		mainActivity = activity;
		this.res = res;
		iconContextMenu = new IconContextMenu(activity, VR.id.MENU_LOCAL);
	}

	public ChannelSftp channel;
	LayoutInflater inflater;
	MenuInflater menuinflater;

	public void setChannel(ChannelSftp channel) {
		this.channel = channel;
	}

	public ChannelSftp getChannel() {
		return this.channel;
	}

	public Object instantiateItem(View collection, int position) {

		inflater = (LayoutInflater) collection.getContext().getSystemService(
				Context.LAYOUT_INFLATER_SERVICE);
		menuinflater = new MenuInflater(collection.getContext());
		int resId = 0;
		switch (position) {
		case 0: {
			if (connect) {
				View v0 = showRemoteFileAtLogin(resId, collection);
				return v0;
			} else {
				View v0 = showAccountAtLogin(resId, collection);
				return v0;
			}

		}
		case 1:
			myListAdapter = new LocalFileAdapter(inflater);
			if (isSearch) {
				myListAdapter.listFiles.clear();
				Log.v("viet", "setadatalocal");
				VFile file;
				int columnIndexPath = CursorSearch
						.getColumnIndexOrThrow(LocalSearchDatabase.KEY_DEFINITION);
				CursorSearch.moveToFirst();
				while (CursorSearch.getPosition() < CursorSearch.getCount()) {
					file = new VFile(CursorSearch.getString(columnIndexPath));
					myListAdapter.listFiles.add(file);
					CursorSearch.moveToNext();
				}
				isSearch = false;
			}
			resId = R.layout.localview;
			View v = inflater.inflate(resId, null);
			ltwLocal = (ListView) v.findViewById(R.id.ltwLocal);
			ltwLocal.setAdapter(myListAdapter);
			ltwLocal.setOnItemClickListener(onitemclick);
			ltwLocal.setAlwaysDrawnWithCacheEnabled(false);
			((ViewPager) collection).addView(v, 0);
			ltwLocal.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {
					itemCurrentId = position;
					iconContextMenu.RemoveAll();
					iconContextMenu.addItem(res, "Upload",
							R.drawable.v_menu_upload, VR.id.UPLOAD);
					iconContextMenu.addItem(res, "Copy",
							R.drawable.v_menu_copy, VR.id.COPY);
					iconContextMenu.addItem(res, "Cut", R.drawable.v_menu_cut,
							VR.id.CUT);
					iconContextMenu.addItem(res, "Rename",
							R.drawable.v_menu_rename, VR.id.RENAME);
					iconContextMenu.addItem(res, "Delete",
							R.drawable.v_menu_delete, VR.id.DELETE);
					iconContextMenu.addItem(res, "Compress",
							R.drawable.v_menu_compress, VR.id.COMPRESS);
					iconContextMenu.addItem(res, "Compress",
							R.drawable.icon_folder, VR.id.NEWFOLDER);
					iconContextMenu.addItem(res, "New folder",
							R.drawable.v_menu_selectall, VR.id.SELECTALL);
					mainActivity.showDialog(VR.id.MENU_LOCAL);
					return false;
				}
			});
			return v;
		case 2:
			resId = R.layout.localview;
			break;
		case 3:
			resId = R.layout.localview;
			break;
		}

		View view = inflater.inflate(resId, null);
		((ViewPager) collection).addView(view, 0);
		return view;
	}

	public VFile GetItemAt(int position) {
		return (VFile) ltwLocal.getItemAtPosition(position);
	}

	public List<VFile> GetItemsChecked() {
		List<VFile> files = new ArrayList<VFile>();
		for (VFile file : myListAdapter.listFiles) {
			if (file.check)
				files.add(file);
		}
		return files;
	}

	public String GetPathFolderLocal() {
		return myListAdapter.getPath();
	}

	public Object getSftpItemSelected(int position) {
		return (Object) ltwSftp.getItemAtPosition(position);
	}

	@Override
	public void destroyItem(View arg0, int arg1, Object arg2) {
		((ViewPager) arg0).removeView((View) arg2);
	}

	@Override
	public boolean isViewFromObject(View arg0, Object arg1) {
		return (arg0 == ((View) arg1));
	}

	@Override
	public Parcelable saveState() {
		return null;
	}

	@Override
	public void finishUpdate(View arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void restoreState(Parcelable arg0, ClassLoader arg1) {
		// TODO Auto-generated method stub
	}

	@Override
	public void startUpdate(View arg0) {
		// TODO Auto-generated method stub
	}

	// On listener
	private OnItemClickListener onitemclick = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View v, int position,
				long arg3) {
			// TODO Auto-generated method stub
			Log.v("viet", String.valueOf(ltwLocal.getCount()));
			((CheckBox) (v.findViewById(R.id.checkBox1))).setChecked(true);
			if (myListAdapter.isMultiselect) {
				myListAdapter.getItem(position).check = !myListAdapter
						.getItem(position).check;
			} else {
				try {
					VFile FileOpen = (VFile) ltwLocal
							.getItemAtPosition(position);
					if (FileOpen.IsDirectory()) {
						myListAdapter.SetPath(((VFile) ltwLocal
								.getItemAtPosition(position)).getPath());
						myListAdapter.notifyDataSetInvalidated();
					} else {
						Uri uriFileOpen = FileOpen.getUri();
						Intent i = new Intent();
						i.setAction(android.content.Intent.ACTION_VIEW);
						i.setDataAndType(uriFileOpen,
								InstalledApp.getStringType(FileOpen.getExt()));
						mainActivity.startActivity(i);
					}
				} catch (Exception e) {
					Toast.makeText(mainActivity.getApplicationContext(),
							"Can't open", Toast.LENGTH_SHORT);
				}
			}
		}
	};

	// onclick sftp
	private OnItemClickListener onitemclicksftp = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub

			String currentPath = null;

			try {
				currentPath = channel.pwd();
			} catch (SftpException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			String folderClicked = null;
			Object obj = ltwSftp.getItemAtPosition(position);
			folderClicked = ((com.jcraft.jsch.ChannelSftp.LsEntry) obj)
					.getFilename();

			String nextPath = currentPath + "/" + folderClicked;

			if (((com.jcraft.jsch.ChannelSftp.LsEntry) obj).getAttrs().isDir()) {
				try {
					remoteFileAdapter.setPath(nextPath, channel);
				} catch (SftpException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// else //se xu ly o day neu nhu muon thuc hien cac hanh dong click
			// vao files
		}

	};

	// click tren user
	private OnItemClickListener onitemclickDuy = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			User temp = (User) ltwSftp.getItemAtPosition(position);
			String tempName = temp.getUsername();
			String tempPass = temp.getPassword();
			String tempHost = temp.getHost();
			String temppString = temp.getPort();
			Toast.makeText(mContext, tempName, Toast.LENGTH_SHORT).show();
		}
	};

	public void backSftp() {
		try {
			remoteFileAdapter.setPath(remoteFileAdapter.getFile().GetParent(),
					channel);
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		remoteFileAdapter.notifyDataSetInvalidated();
	}

	public String Back() {
		if (pageCurrent == 1) {
			String path = myListAdapter.GetFile().GetParent();
			myListAdapter.SetPath(path);
			myListAdapter.notifyDataSetInvalidated();
			return path;
		} else {
			try {
				remoteFileAdapter.setPath(remoteFileAdapter.getFile()
						.GetParent(), channel);
			} catch (SftpException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			remoteFileAdapter.notifyDataSetInvalidated();
			return remoteFileAdapter.getFile().GetParent();
		}
	}

	@Override
	public void setPrimaryItem(ViewGroup container, int position, Object object) {
		pageCurrent = position;
	}

	public void Refresh() {
		int x = PagerAdapter.POSITION_NONE;
		switch (pageCurrent) {
		case 0:
			String currentPath;
			try {
				currentPath = remoteFileAdapter.getFile().getCurrentPath();
				remoteFileAdapter.setPath(currentPath, channel);
				remoteFileAdapter.notifyDataSetInvalidated();
				Log.i("duy", currentPath);
			} catch (SftpException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;
		case 1:
			myListAdapter.SetPath(myListAdapter.getPath());
			myListAdapter.notifyDataSetInvalidated();
			break;
		}

	}

	public void setDataLocal(Cursor cursor, ChannelSftp channel) {
		isSearch = true;
		this.CursorSearch = cursor;
		this.channel = channel;
	}

	// show remote file on sftp listview(v0) on sftp server at login time
	public View showRemoteFileAtLogin(int resId, View collection) {
		try {
			remoteFileAdapter = new RemoteFileAdapter(inflater, this.channel);
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resId = R.layout.localview;
		View v0 = inflater.inflate(resId, null);
		ltwSftp = (ListView) v0.findViewById(R.id.ltwLocal);
		ltwSftp.setAdapter(remoteFileAdapter);
		ltwSftp.setOnItemClickListener(onitemclicksftp);
		((ViewPager) collection).addView(v0, 0);
		ltwSftp.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				itemCurrentId = position;
				iconContextMenu.RemoveAll();
				iconContextMenu.addItem(res, "Download", R.drawable.v_menu_cut,
						VR.id.DOWNLOAD);
				iconContextMenu.addItem(res, "Delete",
						R.drawable.v_menu_delete, VR.id.DELETESFTPFILE);
				iconContextMenu.addItem(res, "Make folder",
						R.drawable.iconfolder, VR.id.MAKESFTPFOLDER);
				mainActivity.showDialog(VR.id.MENU_LOCAL);

				return false;
			}
		});
		return v0;
	}

	// show account on sftp listview(v0) at login time
	public View showAccountAtLogin(int resId, View collection) {
		userAdapter = new UserAdapter(inflater, mContext);
		resId = R.layout.localview;
		View v0 = inflater.inflate(resId, null);
		ltwSftp = (ListView) v0.findViewById(R.id.ltwLocal);
		ltwSftp.setAdapter(userAdapter);
		ltwSftp.setOnItemClickListener(onitemclickDuy);
		ltwSftp.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				itemCurrentId = position;
				iconContextMenu.RemoveAll();
				iconContextMenu.addItem(res, "Connect", R.drawable.v_menu_copy,
						VR.id.CONNECT);
				iconContextMenu.addItem(res, "Delete user",
						R.drawable.v_menu_copy, VR.id.DELETEUSER);
				mainActivity.showDialog(VR.id.MENU_SFTP);
				return false;
			}
		});
		((ViewPager) collection).addView(v0, 0);
		return v0;

	}

	public void SelectAll() {
		myListAdapter.isMultiselect = true;
		for (int i = 0; i < myListAdapter.getCount(); i++) {
			myListAdapter.getItem(i).check = true;
		}
		myListAdapter.notifyDataSetInvalidated();
	}
}
